﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using WinForm1.data_access;
using WinForm1.db;
using WinForm1.utils;
using static System.Net.Mime.MediaTypeNames;

namespace WinForm1
{
    public partial class MainForm : Form
    {
        public delegate void FindFormConfirmEventHandler(string findWord);  //检索事件
        private String filePath;    //检索路径
        private List<PathInfos> fileList;   //文件信息 列表
        private int[] IsDESC = { 0, 0, 0, 0, 0 };   //对应每列是否排序，0是未排序
        private List<int> findResult;   //检索结果列表
        private String findWord;    //查找关键词
        private int indexNow;   //当前选中行
        private List<List<String>> fileListToStr;   //addrow()，展示信息列表
        public MainForm()
        {
            InitializeComponent();
            fileList = new List<PathInfos>();
            findResult = new List<int>();
            fileListToStr = new List<List<String>> ();
        }

        /// <summary>
        ///     抽出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Withdraw_Click(object sender, EventArgs e)
        {
            filePath = FindPath.Text;
            if (filePath.Length <= 0)
            {
                MessageBox.Show("请输入要检索的路径。", "提示");
                return;
            }
            fileList.Clear();
            int count = OutAndInFileInfos.LoadFileByPath(ref fileList, filePath, IsChecked.Checked);
            if (count <= 0)
            {
                dataGridView1.Rows.Clear();
                dataGridView1.Rows.Add(1);
                MessageBox.Show("请输入有效的访问目录。", "提示");
                return;
            }
            FileListConvert.ListToStr(ref fileListToStr, fileList);
            AddRow();
        }

        /// <summary>
        ///     检索关键词
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Find_Click(object sender, EventArgs e)
        {
            if (fileList.Count <= 0)
            {
                MessageBox.Show("没有可搜索的列表。","提示");
                return;
            }
            FindForm findForm = new FindForm();
            findForm.StartPosition = FormStartPosition.CenterParent;
            findForm.FindFormConfirm += FindPathWord;
            findForm.ShowDialog();

        }

        /// <summary>
        ///     窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            
            //根据Header和所有单元格的内容自动调整行的高度
            //dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            //添加五列
            for (int i = 0; i < 5; i++)
            {
                dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
                //列自适应
                //dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView1.Columns[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;  //关闭默认排序，以程序控制
            }
            //总宽度与form宽度一致
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            //列标题
            dataGridView1.Columns[0].HeaderText = "ファイル名";
            dataGridView1.Columns[1].HeaderText = "路径";
            dataGridView1.Columns[2].HeaderText = "類型";
            dataGridView1.Columns[3].HeaderText = "大小";
            dataGridView1.Columns[4].HeaderText = "日期";
            //设置表的字体与字号
            dataGridView1.Font = new Font("MS UI Gothic", 11);
            dataGridView1.Rows.Add(1);
        }

        /// <summary>
        ///     展示文件信息
        /// </summary>
        private void AddRow()
        {  
            if (fileListToStr.Count > 0)
            {
                dataGridView1.Rows.Clear();
                dataGridView1.Rows.Add(fileListToStr.Count);
                
                for (int i = 0; i < fileListToStr.Count; i++)
                {
                    List<string> list = fileListToStr[i];
                    dataGridView1.Rows[i].Cells[0].Value = list[0];
                    dataGridView1.Rows[i].Cells[1].Value = list[1];
                    dataGridView1.Rows[i].Cells[2].Value = list[2];
                    dataGridView1.Rows[i].Cells[3].Value = list[3];
                    dataGridView1.Rows[i].Cells[4].Value = list[4];
                }
            }
        }

        /// <summary>
        ///     标题头点击事件，排序文件信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                //当前点击列已排序，则反转list
                if (IsDESC[e.ColumnIndex] == 1)
                {
                    IsDESC[e.ColumnIndex] = 0;
                    fileList.Reverse();
                    FileListConvert.ListToStr(ref fileListToStr, fileList);
                    AddRow();
                    return;
                }
            }
            if (e.ColumnIndex == 0)
            {
                fileList = fileList.OrderBy(x => x.FileName).ThenBy(z => z.FilePath).ToList();
            }
            if (e.ColumnIndex == 1)
            {
                fileList = fileList.OrderBy(x => x.FilePath).ThenBy(y => y.FileName).ToList();
            }
            if (e.ColumnIndex == 2)
            {
                fileList = fileList.OrderBy(x => x.FileType).ThenBy(y => y.FileName).ThenBy(z => z.FilePath).ToList();
            }
            if (e.ColumnIndex == 3)
            {
                fileList = fileList.OrderBy(x => x.FileSize).ThenBy(y => y.FileName).ThenBy(z => z.FilePath).ToList();
            }
            if (e.ColumnIndex == 4)
            {
                fileList = fileList.OrderBy(x => x.FileDate).ThenBy(y => y.FileName).ThenBy(z => z.FilePath).ToList();
            }
            //每次只能有一个列在排序
            for (int i = 0; i < IsDESC.Length; i++)
            {
                IsDESC[i] = 0;
            }
            IsDESC[e.ColumnIndex] = 1;
            FileListConvert.ListToStr(ref fileListToStr, fileList);
            AddRow();
        }

        /// <summary>
        ///     终了
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Done_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        ///     快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                Done.PerformClick();
            }
            if (e.KeyCode == Keys.F1)
            {
                CSVIn.PerformClick();
            }
            if (e.KeyCode == Keys.F3)
            {
                Next.PerformClick();
            }
            if (e.KeyCode == Keys.F7)
            {
                Find.PerformClick();
            }
            if (e.KeyCode == Keys.F8)
            {
                Withdraw.PerformClick();
            }
            if (e.KeyCode == Keys.F10)
            {
                CSVOut.PerformClick();
            }
        }

        /// <summary>
        ///     CSV读取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CSVIn_ClickAsync(object sender, EventArgs e)
        {
            BackendClient backendClient = new BackendClient();
            Dictionary<String, Object> response = await backendClient.SendRequest("fileInfos/get",HttpMethod.Get,null);
            if (response == null)
            {
                return;
            }
            if (Convert.ToInt64(response["code"]) == 0)
            {
                fileList.Clear();
                JArray list = (JArray)response["data"];
                FileListConvert.JArrayToList(ref fileListToStr,list);
                FileListConvert.StrToList(fileListToStr,ref fileList);
                AddRow();
                MessageBox.Show("读取成功。","提示");
            }
            else
            {
                MessageBox.Show("读取失败，" + response["message"].ToString(), "提示");
            }
        }

        /// <summary>
        ///     CSV导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CSVOut_Click(object sender, EventArgs e)
        {
            if (fileList.Count <= 0)
            {
                MessageBox.Show("没有可导出的列表。", "提示");
                return;
            }
            BackendClient client = new BackendClient();
            var fileData = new
            {
                fileList = fileListToStr
            };
            Dictionary<String, Object> response = await client.SendRequest("fileInfos/save", HttpMethod.Post, fileData);
            if (response == null)
            {
                return;
            }
            if (Convert.ToInt64(response["code"]) == 0)
            {
                MessageBox.Show("导出成功。","提示");
            }
            else
            {
                MessageBox.Show("导出失败，" + response["message"].ToString(), "提示");
            }
            
        }

        /// <summary>
        ///     关键词检索 下一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Next_Click(object sender, EventArgs e)
        {
            if (findResult.Count <= 0)
            {
                MessageBox.Show("当前没有要进行检索的关键字。", "提示");
                return;
            }
            if (findResult.Count == 1)
            {
                FindPathWords.FindResult(ref findResult, fileList, findWord, 1);
                if (findResult.Count == 1)
                {
                    MessageBox.Show("这已经是最后一条。", "提示");
                    return;
                }
            }
            if (findResult.Count > 1)
            {
                dataGridView1.ClearSelection();
                int index = findResult.IndexOf(indexNow);
                if (index == findResult.Count - 1 )
                {
                    dataGridView1.Rows[findResult[0]].Selected = true;
                    indexNow = findResult[0];
                }
                else
                {
                    dataGridView1.Rows[findResult[index + 1]].Selected = true;
                    indexNow = findResult[index + 1];
                } 
            }
        }

        /// <summary>
        ///     检索方法
        /// </summary>
        /// <param name="findWord"></param>
        private void FindPathWord(String findWord)
        {
            this.findWord = findWord;
            FindPathWords.FindResult(ref findResult, fileList, findWord, 0);
            if (findResult.Count <= 0)
            {
                FindPathWords.FindResult(ref findResult, fileList, findWord, 1);
            }
            if (findResult.Count <= 0)
            {
                MessageBox.Show("検索条件に一致するデータは見つかりません。", "提示");
                return;
            }
            dataGridView1.ClearSelection();
            dataGridView1.Rows[findResult[0]].Selected = true;
            indexNow = findResult[0];
        }

        /// <summary>
        ///     保持当前选中行在画面内
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedCells.Count > 0)
            {
                // 获取最后一个选定单元格所在的行索引
                int rowIndex = dataGridView1.SelectedCells[dataGridView1.SelectedCells.Count - 1].RowIndex;
                // 如果该行非可见，则滚动DataGrid到该行
                //MessageBox.Show(dataGridView1.FirstDisplayedScrollingRowIndex.ToString());
                //MessageBox.Show(dataGridView1.DisplayedRowCount(true).ToString());
                int display = dataGridView1.DisplayedRowCount(true);
                if (display > 5)
                {
                    display -= 5;
                }
                if (rowIndex <= dataGridView1.FirstDisplayedScrollingRowIndex || rowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex + display)
                {
                    dataGridView1.FirstDisplayedScrollingRowIndex = Math.Max(0, rowIndex - display / 2);
                }
            }
        }

        /// <summary>
        ///     点击 选择路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderDlg = new FolderBrowserDialog();
            if (folderDlg.ShowDialog() == DialogResult.OK)
            {
                FindPath.Text = folderDlg.SelectedPath;
            }
            
        }
    }
}
